<?php

namespace App\Http\Controllers\Webdisk\Admin;

use App\Http\Controllers\Controller;
use App\Webdisk\Model\FileCache;
use App\Webdisk\Model\LogInfo;
use App\Webdisk\Model\StatInfo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use function App\Webdisk\makeRes;

class ResourceController extends Controller
{
    function getCacheStat(){
        $res['res_cache_info'] = [
            'last_make_cache' => StatInfo::getInt('last_make_cache'),
            'last_update_cache' => StatInfo::getInt('last_update_cache'),
            'file_count' => StatInfo::getInt('file_count'),
            'dir_count' => StatInfo::getInt('dir_count'),
            'total_file_size' => StatInfo::getInt('total_file_size'),
            'cache_stat' => StatInfo::get('cache_stat')
        ];
        return makeRes(1,$res);
    }

    function updateCache(Request $req){
        $cache_stat = StatInfo::get("cache_stat");
        ini_set("max_execution_time",0);
        if($cache_stat != 'ok'){
            LogInfo::add("执行缓存更新时被拒绝 缓存状态：$cache_stat", $req->attributes->get('user')['user'], LOG_LEVEL_WARNING);
            return makeRes(0,null,'有一项索引相关任务正在进行中....');
        }
        LogInfo::add("开始执行缓存更新", $req->attributes->get('user')['user'], LOG_LEVEL_OP);
        $b = microtime(true);
        StatInfo::set('cache_stat',"updating");
        $res_root = env("RES_ROOT");
        $cache_data = FileCache::all()->toArray();
        $remove = [];
        $valid_cache = [];
        // 查找被删除或被更改的文件
        foreach ($cache_data as $key => $value) {
            $path =$res_root . '/' . $value['path'];
            $is_dir = is_dir($path);
            if( !file_exists($path) ||                              //  条件1：文件不存在
                ( $value['size'] == -1 && !$is_dir) ||              //  条件2：文件夹变成了文件
                ( $value['size'] != -1 && $is_dir)  ||              //  条件3：文件变成了文件夹
                ( !$is_dir && filesize($path) != $value['size'] )   //  条件4：文件大小不一致
            ){
                $remove[] = $value['path'];      //  记录被删除或更改的文件路径
            }else{
                $valid_cache[$value['path']] = 1; //  被有效缓存的文件
            }
        }

        // 查找新增的文件
        $dirs = [$res_root];
        $files = [];
        $dir_count = 0;
        $file_count = 0;
        $total_file_size = 0;
        while (!empty($dirs)) {
            $dir = array_pop($dirs);
            $scanf_res = scandir($dir);
            foreach ($scanf_res as $key => $value) {
                if($value != '.' && $value != '..'){
                    $path = "$dir/$value";
                    $relat_path = str_replace($res_root,'',$path);
                    $files[$relat_path] = $path;
                    if(is_dir($path)){
                        $dirs[] = $path;
                        $dir_count++;
                    }else{
                        $file_count++;
                        $total_file_size+=filesize($path);
                    }
                }
            }
        }
        $new = array_diff_key($files,$valid_cache);

        // 移除失效缓存
        $t = FileCache::whereIn('path',$remove)->delete();

        // 添加新增有效缓存
        $new_data = [];
        foreach ($new as $relat_path => $path) {
            $path_arr = explode('/',$path);
            $new_data[] = [
                'path'=>$relat_path,
                'md5'=>is_file($path) ? md5($path) : '-',
                'size'=>is_file($path) ? filesize($path) : '-1',
                'name'=> array_pop($path_arr)
            ];
        }
        FileCache::insert($new_data);
        $e = microtime(true);
        StatInfo::set("cache_stat",'ok');
        StatInfo::set('last_update_cache',time());
        StatInfo::set("file_count",$file_count);
        StatInfo::set("dir_count",$dir_count);
        StatInfo::set("total_file_size",$total_file_size);
        $time = (($e - $b)*1000).'ms';
        LogInfo::add("缓存更新执行完成 耗时：$time 新文件：". count($new) . " 移除：" . count($remove), $req->attributes->get('user')['user'], LOG_LEVEL_OP);
        return makeRes(1,[
            'time'=>$time,
            'new'=>count($new),
            'remove'=>count($remove)
        ]);
    }

    //
    function makeCache(Request $req){
        ini_set("max_execution_time",0);
        $cache_stat = StatInfo::get("cache_stat");
        if( $cache_stat != 'ok'){
            LogInfo::add("执行缓存创建/重建时被拒绝 缓存状态：$cache_stat", $req->attributes->get('user')['user'], LOG_LEVEL_WARNING);
            return makeRes(0,null,'有一项索引相关任务正在进行中....');
        }
        LogInfo::add("开始执行缓存创建/创建", $req->attributes->get('user')['user'], LOG_LEVEL_OP);
        StatInfo::set("last_make_cache",time());
        StatInfo::set("cache_stat","making");
        $start_time = time();
        DB::table('file_cache')->delete();
        $res_root = env("RES_ROOT");
        $dirs = [];
        $dirs[] = $res_root;
        $file_c = 0;
        $dir_c = 0;
        $total_size = 0;
        $cache_info = [];
        while (!empty($dirs)) {
            $dir = array_pop($dirs);
            $scanf_res = scandir($dir);
            foreach ($scanf_res as $key => $value) {
                if($value != '.' && $value != '..'){
                    $path = "$dir/$value";
                    $relat_path = str_replace($res_root,'',$path);
                    if(is_dir($path)){
                        $dirs[] = $path;
                        $dir_c ++;
                        $cache_info[] = [
                            'path'=>$relat_path,
                            'md5'=>'-',
                            'size'=>-1,
                            'name'=>$value
                        ];
                    }else{
                        $file_c ++;
                        $file_size = filesize($path);
                        $total_size += $file_size;
                        $cache_info[] = [
                            'path'=>$relat_path,
                            'md5'=>md5($path),
                            'size'=>$file_size,
                            'name'=>$value
                        ];
                    }
                    if(count($cache_info) >= 500){
                        FileCache::insert($cache_info);
                        $cache_info = [];
                    }
                }
            }
        }
        if(count($cache_info)>0){
            FileCache::insert($cache_info);
        }
        $end_time = time();
        $use_time = $end_time - $start_time;
        LogInfo::add("缓存创建/重建执行完成 耗时：$use_time 文件数：$file_c 目录数：$dir_c 总大小 $total_size", $req->attributes->get('user')['user'], LOG_LEVEL_OP);
        StatInfo::set("file_count",$file_c);
        StatInfo::set("dir_count",$dir_c);
        StatInfo::set("total_file_size",$total_size);
        StatInfo::set("cache_stat","ok");
        return makeRes(1,[
            'file_count'=>$file_c,
            'dir_count'=>$dir_c,
            'total_file_size'=>$total_size,
            'time'=>$use_time
        ]);
    }
}
